package com.mobzilla.activity;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MbzActivity extends Activity {

  public static final String BASE_URL = "http://172.19.194.33:3000";
  
  private ProgressDialog mDialog;

    
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      mDialog = new ProgressDialog(this);
      
      // Send a HTTP GET Request to get bug details
      new HTTPRequestAsync().execute(BASE_URL + "/bug/2");
      
      // Send a HTTP GET Request to get bug count
      new HTTPRequestAsync().execute(BASE_URL + "/count");
      
      // Send a HTTP POST Request to create a new bug
      JSONObject json = new JSONObject();
      String postJsonData = null;
      try {
        json.put("component", "TestComponent");
        json.put("product", "TestProduct");
        json.put("summary", "This is a test bug for geekathon");
        json.put("version", "unspecified");
        json.put("op_sys", "Mac OS");
        json.put("platform", "PC");
        postJsonData = json.toString();
      } catch (JSONException e) {
        e.printStackTrace(); 
        return;
      }
      
      new CreateObjectAsync()
        .execute(BASE_URL + "/bug?username=username@foo.com&password=password", postJsonData);
                  
      mDialog.show(); 
      
  }

  /** Used to make aysnc GET requests **/
  private class HTTPRequestAsync extends AsyncTask<String, Void, String> {
    
    @Override
    protected String doInBackground(String... params) {           
      String url = params[0];
      DefaultHttpClient client = new DefaultHttpClient();      
      HttpGet getRequest = new HttpGet(url);
      try {
        HttpResponse getResponse = client.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
          Log.w("Mobzilla", "Error " + statusCode + " for URL " + url);
          return null;
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        if (getResponseEntity != null) {
          return EntityUtils.toString(getResponseEntity);
        }
      } catch (IOException e) {
        getRequest.abort();
        Log.w("Mobzilla", "Error for URL " + url, e);
      }

      return null;      
    }
    
    @Override
    protected void onPostExecute(final String result) {
      mDialog.hide();
      Toast.makeText(MbzActivity.this, "Response: " + result, Toast.LENGTH_LONG).show();     
      return;
    }    
  }
  
  /** Used to make aysnc POST requests **/
  private class CreateObjectAsync extends AsyncTask<String, Void, String> {
    
    @Override
    protected String doInBackground(String... params) {  
      String url = params[0];            
      String jsonBody = params[1]; 
      DefaultHttpClient client = new DefaultHttpClient();
      HttpPost postRequest = new HttpPost(url);
      try {
        StringEntity se = new StringEntity(jsonBody);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        postRequest.setEntity(se);
        
        postRequest.setHeader("Accept", "application/json");
        postRequest.setHeader("Content-Type", "application/json");
              
        HttpResponse response = client.execute(postRequest);
        HttpEntity postResponseEntity = response.getEntity();
        if (postResponseEntity != null) {
          return EntityUtils.toString(postResponseEntity);
        }
      } catch (IOException e) {
        postRequest.abort();
        Log.w("DB", "Error for URL " + url, e);
      }
      Log.w("DB", "Returning null...");
      return null;
    }
    
    @Override
    protected void onPostExecute(final String result) {
      // Did it work?
      mDialog.hide();
      Toast.makeText(MbzActivity.this, "Response: " + result, Toast.LENGTH_LONG).show();
      return;
    }    
  }


}
